package net.cn_su.sharpeyes.activity;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.WindowManager;
import android.widget.ProgressBar;

import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import net.cn_su.sharpeyes.R;
import net.cn_su.sharpeyes.application.SuApplication;
import net.cn_su.sharpeyes.pref.ServerInfo_;
import net.cn_su.sharpeyes.utils.UIUtil;
import net.cn_su.sharpeyes.utils.http.HttpClient;
import net.cn_su.sharpeyes.utils.http.HttpUrl;
import net.cn_su.sharpeyes.view.other.ClearEditText;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.App;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Fullscreen;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.sharedpreferences.Pref;
import org.json.JSONObject;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import cz.msebera.android.httpclient.Header;

/**
 * 注册
 */
@EActivity(R.layout.activity_regist)
@Fullscreen
public class RegistActivity extends AppCompatActivity {

    @ViewById
    ClearEditText et_acount, et_pwd, et_name;
    @ViewById
    ProgressBar progressBar;


    @App
    protected SuApplication suApplication;
    @Pref
    protected ServerInfo_ serverInfo;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    }

    @AfterViews
    protected void initData() {



    }

    @Click(R.id.btn_back)
    protected void back() {
        finish();
    }

    @Click(R.id.tv_confirm)
    protected void confirmBtnClick() {

        if (!isMobile(et_acount.getText().toString())) {
            et_acount.requestFocus();
            UIUtil.showToast(this, "请输入正确的手机号");
            return;
        }
        if (et_name.getText().toString().length() == 0) {
            et_name.requestFocus();
            UIUtil.showToast(this, "请输入姓名");
            return;
        }
        if (et_pwd.getText().toString().length() < 8) {
            et_pwd.requestFocus();
            UIUtil.showToast(this, "密码至少8位");
            return;
        }

        registServer();


    }

    private void registServer() {

        progressBar.setVisibility(View.VISIBLE);

        RequestParams params = new RequestParams();
        params.add("phone", et_acount.getText().toString());
        params.add("name", et_name.getText().toString());
        params.add("password", et_pwd.getText().toString());


        HttpClient.post(this, HttpUrl.CREATE_USER, params, new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                if (progressBar != null) {
                    progressBar.setVisibility(View.GONE);
                }

                //Logger.v("response==" + response);
                // 保存登录信息
                try {
                    JSONObject server = response.getJSONObject("server");
                    serverInfo.serverAddress().put(server.getString("url"));
                    serverInfo.hikAccount().put(server.getString("account"));
                    serverInfo.hikPassword().put(server.getString("password"));

                    serverInfo.userId().put(response.getInt("id"));

                    //记录账号信息
                    serverInfo.localAccount().put(et_acount.getText().toString());
                    serverInfo.localPassword().put(et_pwd.getText().toString());
                    serverInfo.userName().put(response.getString("name"));
                    serverInfo.isLogin().put(true);
                    //  用一个字段来判断是否是注册登录跳转
                    OrgChooseActivity_.intent(RegistActivity.this).extra("flag", true).start();
                    setResult(RESULT_OK);
                    finish();


                } catch (Exception e) {
                    e.printStackTrace();
                    if (progressBar != null) {
                        progressBar.setVisibility(View.GONE);
                    }
                    UIUtil.showToast(RegistActivity.this, "注册失败");

                }
            }


            @Override
            public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
                if (progressBar != null) {
                    progressBar.setVisibility(View.GONE);
                }
                UIUtil.showToast(RegistActivity.this, "注册失败");
                try {
                    //Logger.d(errorResponse.getString("error_description"));
                } catch (Exception e) {

                }

                //  showLoading();
            }


        });


    }


    /**
     * 判断手机号码
     */
    public boolean isMobile(String mobiles) {
        if (mobiles.length() < 11)
            return false;
        Pattern pattern = Pattern.compile("^0?(13[0-9]|15[0-9]|18[0-9]|14[57]|17[0-9])[0-9]{8}$");
        Matcher matcher = pattern.matcher(mobiles);
        return matcher.matches();
    }
}
